<?php

namespace app\api\controller;

use app\common\services\UploadService;
use app\common\traits\ApiTrait;
use support\Request;
use support\Response;
use think\Exception;
use think\facade\Db;
use app\extend\WxUtil\WxTool;
use Tinywan\Jwt\JwtToken;

class UserController
{
    use ApiTrait;

    /**
     * 不需要登录的方法
     */
    protected $noNeedLogin = ['getExamine', 'wxLogin', 'upload'];

    /**
     * 小程序审核状态获取
     * @return void
     */
    public function getExamine(Request $request): Response
    {
        return $this->reSuccess('数据获取成功', ['is_examine' => sysconfig('site', 'is_examine')]);
    }

    /**
     * 微信小程序快速登录
     */
    public function wxLogin(Request $request) : Response
    {
        if (!request()->isPost()) {
            return $this->reError('请求方式错误');
        }

        $wxcode = $request->post('wxcode', '');
        $wxTool = new WxTool();
        $miniapp_appid = Db::name('system_config')->where(['name' => 'miniapp_appid'])->value('value');
        $miniapp_appsecret = Db::name('system_config')->where(['name' => 'miniapp_appsecret'])->value('value');
        $wxSession = $wxTool->jscode2session($miniapp_appid, $miniapp_appsecret, $wxcode);
        if(empty($wxSession)) {
            return $this->reError('获取微信数据失败。'.$wxTool->error);
        }
        $user = Db::name('user')->where(['openid' => $wxSession['openid']])->find();
        if(!empty($user)) {
            // status = 2 是登录
            return $this->reSuccess('登录成功', ['token' => JwtToken::generateToken(['id' => $user['id']])['access_token'], 'status' => 2]);
        }else{
            $insert = ['avatar_url' => getenv('API_HOST').'/static/avatar/'.mt_rand(1, 100).'.jpg', 'nickname' => '用户'.mt_rand(100000, 999999), 'openid' => $wxSession['openid'], 'create_time' => time()];
            $userId = Db::name('user')->insertGetId($insert);
            if(!empty($userId)) {
                // status = 1 是注册 (首次登录)
                return $this->reSuccess('登录成功', ['token' => JwtToken::generateToken(['id' => $userId])['access_token'], 'status' => 1]);
            }else{
                return $this->reError('登录失败');
            }
        }
    }

    /**
     * 修改用户信息
     * @param Request $request
     * @return Response
     * @throws \think\db\exception\DbException
     */
    public function saveUserInfo(Request $request): Response
    {
        if (!request()->isPost()) {
            return $this->reError('请求方式错误');
        }

        $nickname = $request->post('nickname', '');
        if (!empty($nickname)) {
            $update['nickname'] = $nickname;
        }
        $avatar_url = $request->post('avatar_url', '');
        if (!empty($avatar_url)) {
            $update['avatar_url'] = $avatar_url;
        }
        if (!empty($update)) {
            Db::name('user')->where(['id' => JwtToken::getExtend()['id']])->update($update);
        }
        return $this->reSuccess('修改成功');
    }

    /**
     * 个人中心
     */
    public function dashboard(Request $request): Response
    {
        $activityId = $request->get('activityId');
        if (empty($activityId) || $activityId == 'false') {
            return $this->reError('请重新进入活动');
        }

        $data = Db::name('user')->where(['id' => JwtToken::getExtend()['id']])->field('id, nickname, avatar_url')->find();
        $data['role'] = Db::name('activity_user_role')->where(['activity_id' => $activityId, 'user_id' => JwtToken::getExtend()['id']])->value('role', 0);
        $data['miniapp_original_id'] = sysconfig('wechat', 'miniapp_original_id');
        return $this->reSuccess('成功', $data);
    }

    /**
     * 我的订单
     * @return void
     */
    public function myOrder(Request $request): Response
    {
        if (!request()->isGet()) {
            return $this->reError('请求方式错误');
        }

        $activityId = $request->get('activityId');
        if (empty($activityId) || $activityId == 'false') {
            return $this->reError('请重新进入活动');
        }

        $page = $request->get('page');
        $limit = $request->get('limit');

        $data = Db::name('order')
            ->where(['activity_id' => $activityId, 'user_id' => JwtToken::getExtend()['id'], 'order_status' => 2])
            ->order('id desc')->page($page, $limit)->select()->toArray();
        return $this->reSuccess('数据获取成功', $data);
    }

    /**
     * 我的推荐
     * @return void
     */
    public function myRecom(Request $request): Response
    {
        if (!request()->isGet()) {
            return $this->reError('请求方式错误');
        }

        $activityId = $request->get('activityId');
        if (empty($activityId) || $activityId == 'false') {
            return $this->reError('请重新进入活动');
        }

        $page = $request->get('page');
        $limit = $request->get('limit');

        $data = Db::name('order')
            ->alias('a')
            ->join('user b', 'a.user_id = b.id')
            ->where(['a.activity_id' => $activityId, 'a.recom_user_id' => JwtToken::getExtend()['id']])
            ->field('a.*, b.nickname, b.avatar_url')
            ->order('a.id desc')->page($page, $limit)->select()->toArray();
        return $this->reSuccess('数据获取成功', $data);
    }

    /**
     * 推荐奖励
     * @return void
     */
    public function myRecomReward(Request $request): Response
    {
        if (!request()->isGet()) {
            return $this->reError('请求方式错误');
        }

        $activityId = $request->get('activityId');
        if (empty($activityId) || $activityId == 'false') {
            return $this->reError('请重新进入活动');
        }

        $page = $request->get('page');
        $limit = $request->get('limit');

        // 总佣金
        $data['total'] = Db::name('payment_disburse')->where(['activity_id' => $activityId, 'recom_user_id' => JwtToken::getExtend()['id']])->sum('amount');
        // 已发出
        $data['issue'] = Db::name('payment_disburse')->where(['activity_id' => $activityId, 'recom_user_id' => JwtToken::getExtend()['id'], 'status' => 1])->sum('amount');

        $list = Db::name('payment_disburse')
            ->alias('a')
            ->join('user b', 'a.user_id = b.id')
            ->where(['a.activity_id' => $activityId, 'a.recom_user_id' => JwtToken::getExtend()['id']])
            ->field('a.*, b.nickname, b.avatar_url')
            ->order('a.id desc')->page($page, $limit)->select()->toArray();
        return $this->reSuccess('数据获取成功', ['data' => $data, 'list' => $list]);
    }

    /**
     * 我的礼品
     * @return void
     */
    public function myActivityPrize(Request $request): Response
    {
        if (!request()->isGet()) {
            return $this->reError('请求方式错误');
        }

        $activityId = $request->get('activityId');
        if (empty($activityId) || $activityId == 'false') {
            return $this->reError('请重新进入活动');
        }

        $page = $request->get('page');
        $limit = $request->get('limit');

        $data = Db::name('payment_activity_prize')
            ->where(['activity_id' => $activityId, 'user_id' => JwtToken::getExtend()['id']])
            ->order('id desc')
            ->page($page, $limit)->select()->toArray();
        return $this->reSuccess('数据获取成功', $data);
    }

    /**
     * 我的盲盒
     * @return void
     */
    public function myPlatformBoxPrize(Request $request): Response
    {
        if (!request()->isGet()) {
            return $this->reError('请求方式错误');
        }

        $activityId = $request->get('activityId');
        if (empty($activityId) || $activityId == 'false') {
            return $this->reError('请重新进入活动');
        }

        $page = $request->get('page');
        $limit = $request->get('limit');

        $data = Db::name('payment_platform_box')
            ->where(['activity_id' => $activityId, 'user_id' => JwtToken::getExtend()['id']])
            ->order('id desc')
            ->page($page, $limit)->select()->toArray();
        return $this->reSuccess('数据获取成功', $data);
    }

    /**
     * @desc  上传文件
     * @param Request $request
     * @return Response
     */
    public function upload(Request $request): Response
    {
        if (!request()->isPost()) {
            return $this->reError('请求方式错误');
        }
        $type = $request->input('type', '');
        $data = [
            'file'        => $request->file($type == 'editor' ? 'upload' : 'file'),
        ];
        $uploadConfig = sysconfig('upload');
        $file = $data['file'];
        if (!in_array($file->getUploadExtension(), explode(',', $uploadConfig['upload_allow_ext']))) {
            return $this->reError('上传文件类型不在允许范围');
        }
        if ($file->getSize() > $uploadConfig['upload_allow_size']) {
            return $this->reError('文件大小超过预设值');
        }
        $upload_type = $uploadConfig['upload_type'];
        try {
            $upload = UploadService::instance()->setConfig($uploadConfig)->$upload_type($file, $type);
        } catch (\Exception $e) {
            return $this->reError($e->getMessage());
        }
        $code = $upload['code'] ?? 0;
        if ($code == 0) {
            return $this->reError($upload['data'] ?? '');
        } else {
            if ($upload_type == 'local') {
                $upload['data']['url'] = getenv('API_HOST').$upload['data']['url'];
            }
            return $this->reSuccess('上传成功', $upload['data'] ?? '');
        }
    }
}
